package com.ly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.entity.Score;
import com.ly.mapper.ActivityMapper;
import com.ly.mapper.ScoreMapper;
import com.ly.pojo.vo.ActivityVO;
import com.ly.recommend.CoreMath;
import com.ly.recommend.ItemCF;
import com.ly.recommend.ScoreRecommend;
import com.ly.recommend.UserCF;
import com.ly.service.SocreService;
import com.ly.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : 黑渊白花
 * @ClassName SocreServiceImpl
 * @date : 2025/5/11 15:53
 * @Description
 */
@Service
@Slf4j
public class SocreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements SocreService {

    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    private ActivityMapper activityMapper;

    private Map<Integer, Map<Integer, Double>> loadRatingsFormDB(){
        Map<Integer, Map<Integer, Double>> userRatings = new HashMap<>();
        List<Score> scores = scoreMapper.selectList(null);
        for(Score score: scores){
            userRatings.computeIfAbsent(score.getStuId(),
                    k->new HashMap<>()).put(score.getActId(),score.getScore());
        }
        return userRatings;
    }


    @Override
    public List<ActivityVO> recommend(Integer stuId) {
        QueryWrapper qw=new QueryWrapper();
        qw.eq("stu_id",stuId);
        List list = scoreMapper.selectList(qw);
        //如果用户从未评价过,则推荐活动参加人数最高的4个活动，反之评价过则按协同过滤算法进行推荐
        if(list.isEmpty()){
            // QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
            // queryWrapper.eq("status",2).orderByDesc("enter_num").last("limit 4");
            return activityMapper.getFourAct();
        }else{
            List<ActivityVO> activityList=new ArrayList<>();
            Map<Integer, Map<Integer, Double>> integerMapMap = loadRatingsFormDB();
            List<Integer> similarUsers = ScoreRecommend.findTopThreeSimilarUsers(stuId, integerMapMap);
            List<Map.Entry<Integer, Double>> entries = ScoreRecommend.recommendStickOnSimilarUsers(integerMapMap, similarUsers, stuId);
            for(Map.Entry<Integer,Double> map : entries){
                ActivityVO activity = activityMapper.getActById(map.getKey());
                activityList.add(activity);
            }
            if(activityList.isEmpty()){
                return activityMapper.getFourAct();
            }else{

                return activityList;
            }
        }
    }

    //基于物品的推荐
    @Override
    public List<ActivityVO> recommendOther1(Score score) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("stu_id", score.getStuId());
        qw.eq("act_id",score.getActId());
        List list = scoreMapper.selectList(qw);
        //如果用户从未评价过,则推荐活动参加人数最高的4个活动，反之评价过则按协同过滤算法进行推荐
        if (list.isEmpty()) {
            // QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
            // queryWrapper.eq("status",2).orderByDesc("enter_num").last("limit 4");
            List<ActivityVO> fourAct = activityMapper.getFourAct();
            return fourAct;
        } else {
            List<ActivityVO> activityList = new ArrayList<>();
            List<Score> scores = scoreMapper.selectList(null);
            List<Integer> integers = CoreMath.itemCFRecommend(score.getActId(),scores);
            for (Integer id:integers){
                ActivityVO activity = activityMapper.getActById(id);
                activityList.add(activity);
            }
            if (activityList.isEmpty()) {
                List<ActivityVO> fourAct = activityMapper.getFourAct();
                return fourAct;
            } else {
                return activityList;
            }
        }
    }

    @Override
    public List<ActivityVO> recommendUser(Integer stuId) {
        QueryWrapper qw=new QueryWrapper();
        qw.eq("stu_id",stuId);
        List list = scoreMapper.selectList(qw);
        //如果用户从未评价过,则推荐活动参加人数最高的4个活动，反之评价过则按协同过滤算法进行推荐
        if(list.isEmpty()){
            // QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
            // queryWrapper.eq("status",2).orderByDesc("enter_num").last("limit 4");
            List<ActivityVO> fourAct = activityMapper.getFourAct();
            return fourAct;
        }else{
            List<ActivityVO> activityList=new ArrayList<>();
            //推荐数量
            int numRecommendations = 4;
            Map<Integer, Map<Integer, Double>> integerMapMap = loadRatingsFormDB();
            List<Integer> recommend = UserCF.recommend(integerMapMap, stuId, numRecommendations);
            for (Integer id:recommend){
                ActivityVO activity = activityMapper.getActById(id);
                activityList.add(activity);
            }
            if(activityList.isEmpty()){
                List<ActivityVO> fourAct = activityMapper.getFourAct();
                return fourAct;
            }else{
                return activityList;
            }
        }
    }

    @Override
    public List<ActivityVO> recommendItem(Integer stuId) {
        QueryWrapper qw=new QueryWrapper();
        qw.eq("stu_id",stuId);
        List list = scoreMapper.selectList(qw);
        //如果用户从未评价过,则推荐活动参加人数最高的4个活动，反之评价过则按协同过滤算法进行推荐
        if(list.isEmpty()){
            // QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
            // queryWrapper.eq("status",2).orderByDesc("enter_num").last("limit 4");
            List<ActivityVO> fourAct = activityMapper.getFourAct();
            return fourAct;
        }else{
            List<ActivityVO> activityList=new ArrayList<>();
            //推荐数量
            int numRecommendations = 4;
            Map<Integer, Map<Integer, Double>> integerMapMap = loadRatingsFormDB();
            List<Integer> recommend = ItemCF.recommend(integerMapMap, stuId, numRecommendations);
            for (Integer id:recommend){
                ActivityVO activity = activityMapper.getActById(id);
                activityList.add(activity);
            }
            if(activityList.isEmpty()){
                List<ActivityVO> fourAct = activityMapper.getFourAct();
                return fourAct;
            }else{
                return activityList;
            }
        }
    }

    @Override
    public Result isPointThisAct(Score score) {
        QueryWrapper<Score> qw = new QueryWrapper<>();
        qw.eq("stu_id",score.getStuId());
        qw.eq("act_id",score.getActId());
        Score score1 = scoreMapper.selectOne(qw);
        if(score1 == null){
            return Result.warn("暂无评分");
        }
        return Result.success(score1);
    }

    @Override
    public Result evaluation(Score score) {
        QueryWrapper<Score> qw = new QueryWrapper<>();
        qw.eq("stu_id",score.getStuId());
        qw.eq("act_id",score.getActId());
        Long count = scoreMapper.selectCount(qw);
        if(count>0){
            scoreMapper.updateById(score);
            return Result.success("修改评分成功");
        }else{
            scoreMapper.insert(score);
            return Result.success("评分成功");
        }
    }
}
